package com.iflytek.cosmo.ocr.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * HTML和WORD互转工具类
 *
 */
public class HtmlWordUtil {

	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(HtmlWordUtil.class);

	/**
	 * 
	 * @description 将word转成html并获取html内容
	 * @author manzhang
	 * @create 2016年12月3日上午10:34:28
	 * @version 1.0
	 * @param byte word字节数组
	 * @param type 类型，doc和docx
	 * @return html内容
	 * @throws Exception Exception
	 */
	public static String wordToHtml(byte[] bytes, String type) throws Exception {
		String content = "";

		if ("doc".equals(type)) {
			try {
				content = docToHtml(bytes);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				try {
					content = docxToHtml(bytes);
				} catch (Exception e1) {
					logger.error("word解析失败，错误信息：" + e1);
					throw e1;
				}
			}
		} else if ("docx".equals(type)) {
			try {
				content = docxToHtml(bytes);
			} catch (Exception e) {
				try {
					content = docToHtml(bytes);
				} catch (Exception e1) {
					logger.error("word解析失败，错误信息：" + e1);
					throw e1;
				}
			}
		}

		return content;
	}

	/**
	 * 
	 * @description docx转html
	 * @author manzhang
	 * @create 2016年12月3日上午10:36:02
	 * @version 1.0
	 * @param bytes word字节数组
	 * @return html内容
	 * @throws Exception 异常
	 */
	public static String docxToHtml(byte[] bytes) throws Exception {
		ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
		String content = "";
		XWPFDocument document = new XWPFDocument(inputStream);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		XHTMLOptions options = XHTMLOptions.create();
		options.setIgnoreStylesIfUnused(false);
		options.setFragment(true);
		XHTMLConverter.getInstance().convert(document, out, options);

		content = new String(out.toByteArray(), "UTF-8");
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e1) {
				logger.error(e1.getMessage(), e1);
			}
		}

		return content;
	}

	/**
	 * 
	 * @description doc转html
	 * @author manzhang
	 * @create 2016年12月3日上午10:37:00
	 * @version 1.0
	 * @param bytes word字节数组
	 * @return html内容
	 * @throws Exception 异常
	 */
	public static String docToHtml(byte[] bytes) throws Exception {
		ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
		String content = "";
		HWPFDocument wordWordument = new HWPFDocument(inputStream);
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
						.newDocument());
		wordToHtmlConverter.processDocument(wordWordument);
		org.w3c.dom.Document htmlWordument = wordToHtmlConverter.getDocument();

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlWordument);
		StreamResult streamResult = new StreamResult(out);

		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();

		content = new String(out.toByteArray(), "UTF-8");
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e1) {
				logger.error(e1.getMessage(), e1);
			}
		}

		return content;
	}
}
